import React, { useState, useRef, useEffect } from 'react';
import styles from './CustomerServiceBackend.module.css';

interface Message {
    type: 'customer' | 'agent';
    content: string;
}

export default function CustomerServiceBackend() {
    const [status, setStatus] = useState('状态: 未连接');
    const [messages, setMessages] = useState<Message[]>([]);
    const [inputValue, setInputValue] = useState('');
    const wsRef = useRef<WebSocket | null>(null);
    const messagesEndRef = useRef<HTMLDivElement>(null);
    const lastMessages = useRef<Array<{content: string, sender: string, timestamp: number}>>([]);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const connect = () => {
        const ws = new WebSocket(`ws://${window.location.hostname}:3000/ws`);
        wsRef.current = ws;
        
        ws.onopen = () => {
            setStatus('状态: 已连接');
            ws.send(JSON.stringify({
                type: 'register',
                role: 'agent'
            }));
        };

        ws.onclose = () => {
            setStatus('状态: 连接断开，正在重连...');
            setTimeout(connect, 3000);
        };

        ws.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.type === 'message') {
                    const content = data.content || '';
                    const sender = data.from || 'unknown';
                    const now = Date.now();
                    
                    const isDuplicate = lastMessages.current.some(msg => 
                        msg.content === content && 
                        msg.sender === sender && 
                        now - msg.timestamp < 3000
                    );
                    
                    if (isDuplicate) {
                        console.log('忽略重复消息:', content);
                        return;
                    }
                    
                    lastMessages.current.push({
                        content, 
                        sender, 
                        timestamp: now
                    });
                    
                    if (lastMessages.current.length > 10) {
                        lastMessages.current.shift();
                    }
                    
                    addMessage(content, 'customer');
                }
            } catch (error) {
                console.error('解析消息错误:', error);
            }
        };
    };

    const addMessage = (content: string, type: 'customer' | 'agent') => {
        setMessages(prev => [...prev, { type, content }]);
    };

    const sendMessage = () => {
        const content = inputValue.trim();
        if (!content || !wsRef.current) return;

        wsRef.current.send(JSON.stringify({
            type: 'message',
            content: content
        }));

        addMessage(content, 'agent');
        setInputValue('');
    };

    const handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
        if (event.key === 'Enter') {
            sendMessage();
        }
    };

    useEffect(() => {
        connect();
        return () => {
            if (wsRef.current) {
                wsRef.current.close();
            }
        };
    }, []);

    return (
        <div className={styles.container}>
            <div className={styles.status}>{status}</div>
            <div className={styles.chatContainer}>
                <div className={styles.chatHeader}>
                    客服工作台
                </div>
                <div className={styles.chatMessages}>
                    {messages.map((message, index) => (
                        <div 
                            key={index} 
                            className={`${styles.message} ${styles[`${message.type}Message`]}`}
                        >
                            {message.content}
                        </div>
                    ))}
                    <div ref={messagesEndRef} />
                </div>
                <div className={styles.chatInput}>
                    <input 
                        type="text" 
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        placeholder="输入消息..." 
                        onKeyPress={handleKeyPress}
                    />
                    <button onClick={sendMessage}>发送</button>
                </div>
            </div>
        </div>
    );
} 